
from dvadmin.knowledge.models import Book,Documents
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.decorators import action
from rest_framework import serializers
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse


class BasisSerializer(CustomModelSerializer):
    """
    区块-序列化器
    """
    class Meta:
        model = Book
        fields = "__all__"
        read_only_fields = ["id"]


class BasisViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Book.objects.all()
    serializer_class = BasisSerializer
    extra_filter_backends = []
    permission_classes = []

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        request_data = request.data
        soft_delete = request_data.get('soft_delete',1)
        print(request_data)
        if soft_delete and self.soft_delete:
            instance.is_deleted = 1
            instance.save()
        else:
            self.perform_destroy(instance)

        Documents.objects.filter(book_id =instance.id).update(is_deleted = 1)
        return DetailResponse(data=[], msg="删除成功")
    def list(self, request, *args, **kwargs):
        if self.request.user.is_superuser == 0:
            queryset = self.filter_queryset(self.get_queryset().filter(creator_id = self.request.user.id))
        else:
            queryset = self.filter_queryset(self.get_queryset())


        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True, request=request)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True, request=request)
        return SuccessResponse(data=serializer.data, msg="获取成功")
    @action(methods=['GET'], detail=False)
    def pubilclist(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset().filter(privately_status=1))
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True, request=request)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True, request=request)
        return SuccessResponse(data=serializer.data, msg="获取成功")

    @action(methods=['POST'], detail=False)
    def preface(self, request, *args, **kwargs):
        try:
            bookid =  request.query_params['bookid']
            release_markdown_editor =  request.query_params['release_markdown_editor']
            obj = self.queryset.get(id= bookid)
            obj.preface = release_markdown_editor
            obj.save()
            return SuccessResponse( msg="更新成功")
        except Exception as e:
            return  ErrorResponse(msg=e)
